/*   
 * Copyright 2009-2010 Rob Schoening
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *    http://www.apache.org/licenses/LICENSE-2.0
 *    
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.beaconframework.vaadin.servlet;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;

import com.vaadin.Application;
import com.vaadin.terminal.gwt.server.ApplicationServlet;

public class SecureAplicationServlet extends ApplicationServlet {

    /**
	 * 
	 */
    private static final long serialVersionUID = -4758409699860973878L;

    class UnauthenticatedException extends RuntimeException {

        /**
		 * 
		 */
        private static final long serialVersionUID = 5648195925699967159L;
        // marker exception
    }

    public static final String UNAUTHENTICATED_REDIRECT_URI = "authenticatonRedirectLocation";
    Logger log = LoggerFactory.getLogger(SecureAplicationServlet.class);

    @Override
    protected Application getNewApplication(HttpServletRequest request)
            throws ServletException {

        Authentication e = SecurityContextHolder.getContext()
                .getAuthentication();

        if (e == null) {
            log.info("not authenticated");
            throw new UnauthenticatedException();
        } else if (!e.isAuthenticated()) {
            log.info("not authenticated");
            throw new UnauthenticatedException();
        }
        Application app = super.getNewApplication(request);

        Object principalObject = e.getPrincipal();
        if (principalObject instanceof String) {
            app.setUser(principalObject);
        } else if (principalObject instanceof UserDetails) {
            app.setUser(((UserDetails) principalObject).getUsername());
        }

        return app;
    }

    public String getRedirectUri() {
        String uri = getInitParameter(UNAUTHENTICATED_REDIRECT_URI);
        if (uri == null) {
            uri = "app";
        }
        return uri;
    }

    @Override
    protected void service(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {

        try {

            super.service(request, response);
            return;
        } catch (UnauthenticatedException e) {
            // redirect below
        } catch (ServletException e) {
            Throwable t = e.getRootCause();
            if (t == null || (!(t instanceof UnauthenticatedException))) {
                throw e;
            }
        }
        response.sendRedirect(getRedirectUri());

    }
}
